package com.lucky.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.lucky.util.AESUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @Description: TODO
 * @Author: Jalyson
 * @Date: 2019/10/24 16:57
 */
@ControllerAdvice
public class ResonseBodyWrapper implements ResponseBodyAdvice<Object> {
    /** logger */
    private static final Logger LOGGER = LoggerFactory.getLogger(ResonseBodyWrapper.class);

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        //key 不为空加密
        return encryptKey != null;
    }

    @Value("${lucky.resonsebody.encrypt.key}")
    private String encryptKey;

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest request,
            ServerHttpResponse response) {
        // 然后使用SpringBoot RequestContextHolder 提供的方法来获取Request 对象，来获取请求参数判断需要返回的对应类型
        List<String> encrypt = request.getHeaders().get("encrypt");
        if (encryptKey != null && encrypt != null && "AES256".equals(encrypt.get(0))) {
            // 修改响应头
            try {
                String bodyText = JSONObject.toJSONString(body);
                body = AESUtil.encrypt(encryptKey, bodyText);
                response.getHeaders().add("encrypt", "AES256");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return body;
    }

    /**
     * 检查加密key长度
     */
    @PostConstruct
    public void checkEncryptKey() {
        if (encryptKey != null) {
            if (encryptKey.length() != 16) {
                throw new RuntimeException(
                        "response body encrypt key length error: ${lucky.resonsebody.encrypt.key} length must be 16,but now :" + encryptKey.length() + "(" + encryptKey + ")");
            }
        }
    }

}